import {
	splitMenuLevel,
	findMenu,
	findShowMenu,
	findMenuFirstChild
} from '@/utils/menusUtil'
import Cookies from 'js-cookie'
const menus = {
	state: {
		sidebar: {
			opened: !+Cookies.get('sidebarStatus'),
			hid: false
		},
		menus: {},
		// menuActiveIndex:Cookies.get('menuActiveIndex'),
		sidebarMenus: [],
		sidebarMenusIndex: '',
		curMenu: null,
		codeMenu: null,
		homePageMenu: null,
		shopListMenuActiveShop: null
	},
	mutations: {
		SET_CURMENU: (state, curMenu) => {
			state.curMenu = curMenu
		},
		TOGGLE_SIDEBAR: (state) => {
			if (state.sidebar.opened) {
				Cookies.set('sidebarStatus', 1)
			} else {
				Cookies.set('sidebarStatus', 0)
			}
			state.sidebar.opened = !state.sidebar.opened
		},
		CLOSE_SIDEBAR: (state) => {
			Cookies.set('sidebarStatus', 0)
			state.sidebar.opened = false
		},
		OPEN_SIDEBAR: (state) => {
			if (!+Cookies.get('sidebarStatus')) {
				state.sidebar.opened = true
			}
		},
		REFRESH_CUR_MENU: (state, router) => {
			if (Object.keys(router.meta).length === 0) {
				// 没有meta信息, 直接返回
				state.sidebar.hid = true
				return -1
			}

			const curMenu = splitMenuLevel(router.meta)
			state.sidebar.hid = !(curMenu.length >= 2)
			if (!state.curMenu || curMenu[0].code !== state.curMenu[0].code) {
				state.sidebarMenus = findMenu(state.menus, curMenu[0].code) ?
					findMenu(state.menus, curMenu[0].code).children :
					[]
				state.sidebarMenusIndex = curMenu[curMenu.length - 1].code
			} else {
				state.sidebarMenusIndex = curMenu[curMenu.length - 1].code
			}
			state.curMenu = curMenu
		},

		RELOAD_MENUS: (state, menus) => {
			const showMenu = JSON.parse(JSON.stringify(menus))
			findShowMenu(showMenu)
			state.homePageMenu = findMenuFirstChild(showMenu)
			state.menus = showMenu
		},

		SET_SHOPLISTMENUACTIVESHOP: (state, data) => {
			state.shopListMenuActiveShop = data
		}
	},

	actions: {
		setCurmenu({
			commit
		}, curmenu) {
			console.log(curmenu)
			commit('SET_CURMENU', curmenu)
		},
		ToggleSideBar: ({
			commit
		}) => {
			commit('TOGGLE_SIDEBAR')
		},
		CloseSideBar({
			commit
		}) {
			commit('CLOSE_SIDEBAR')
		},
		OpenSideBar({
			commit
		}) {
			commit('OPEN_SIDEBAR')
		},
		ToggleDevice({
			commit
		}, device) {
			commit('TOGGLE_DEVICE', device)
		},
		ReloadMenus: ({
			commit
		}, menus) => {
			commit('RELOAD_MENUS', menus)
		},
		RefreshCurMenu: ({
			commit
		}, router) => {
			commit('REFRESH_CUR_MENU', router)
		},
		SetShopListMenuActiveShop: ({
			commit
		}, data) => {
			commit('SET_SHOPLISTMENUACTIVESHOP', data)
		}
	}
}

export default menus
